<!--
  登录页面 - 用户身份验证
-->
<template>
  <div class="login-container">
    <!-- 登录表单卡片 -->
    <div class="login-card">
      <div class="login-header">
        <h2 class="login-title">系统登录</h2>
        <p class="login-subtitle">欢迎访问传奇CMS管理系统</p>
      </div>
      
      <div class="login-form">
        <!-- 用户名输入 -->
        <div class="form-item">
          <div class="form-label">用户名</div>
          <div class="input-wrapper">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              size="large"
              clearable
              @keyup.enter="handleLogin"
            />
          </div>
        </div>
        
        <!-- 密码输入 -->
        <div class="form-item">
          <div class="form-label">密码</div>
          <div class="input-wrapper">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              show-password
              clearable
              @keyup.enter="handleLogin"
            />
          </div>
        </div>
        
        <!-- 登录按钮 -->
        <div class="form-item">
          <div class="button-wrapper">
            <el-button
              type="primary"
              size="large"
              class="login-button"
              :loading="loginLoading"
              @click="handleLogin"
            >
              {{ loginLoading ? '登录中...' : '登录' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { 
  ref, 
  reactive, 
  onBeforeMount,
  onMounted, 
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
  onErrorCaptured,
  nextTick 
} from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

// 组件名称
defineOptions({
  name: 'LoginPage'
})

// 路由实例
const router = useRouter()

// 响应式变量声明（按照模板中的顺序）
const loginLoading = ref(false)

// 响应式对象 - 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 响应函数声明（按照模板中的顺序）
/**
 * 处理登录请求
 */
const handleLogin = async () => {
  // 表单验证
  if (!loginForm.username.trim()) {
    ElMessage.warning('请输入用户名')
    return
  }
  if (!loginForm.password.trim()) {
    ElMessage.warning('请输入密码')
    return
  }
  
  loginLoading.value = true
  
  try {
    // 模拟登录API调用
    const response = await mockLoginApi(loginForm)
    
    if (response.code === 200) {
      // 保存token到localStorage
      const token = response.data.token
      localStorage.setItem('token', token)
      localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo))
      
      ElMessage.success('登录成功')
      
      // 跳转到首页
      router.push('/')
    } else {
      ElMessage.error(response.message || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error('登录失败，请稍后重试')
  } finally {
    loginLoading.value = false
  }
}

/**
 * 模拟登录API
 */
const mockLoginApi = (formData) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // 模拟用户验证
      if (formData.username === 'admin' && formData.password === '123456') {
        resolve({
          code: 200,
          message: '登录成功',
          data: {
            token: 'mock_token_' + Date.now(),
            userInfo: {
              id: 1,
              username: 'admin',
              nickname: '管理员',
              avatar: '',
              // 为管理员用户添加所有权限
              permissions: [
                'SUPER_ADMIN',
                'SYSTEM_ADMIN',
                'SYSTEM_USER',
                'SYSTEM_ROLE',
                'SYSTEM_MENU',
                'SYSTEM_AUTH',
                'SYSTEM_BRANCH',
                'SYSTEM_MODULE',
                'SYSTEM_TOKEN',
                'SYSTEM_RECORD',
                'SYSTEM_VERIFY',
                'SYSTEM_SUMMARY'
              ]
            }
          }
        })
      } else {
        resolve({
          code: 401,
          message: '用户名或密码错误'
        })
      }
    }, 1000)
  })
}

// 样式函数声明
/**
 * 获取输入框样式类名
 */
const getInputStyleClass = (isValid) => {
  return isValid ? 'input-valid' : 'input-invalid'
}

// 生命周期钩子
onBeforeMount(() => {
  // 组件挂载前执行的逻辑
  // 检查是否已登录，如果已登录则跳转到首页
  const token = localStorage.getItem('token')
  if (token) {
    router.push('/')
  }
})

onMounted(() => {
  // 组件挂载后执行的逻辑
  console.log('登录页面已加载')
})

onBeforeUpdate(() => {
  // 组件更新之前执行的逻辑
  nextTick(() => {
    // 在DOM更新之后执行的逻辑
  })
})

onUpdated(() => {
  // 组件更新之后执行的逻辑
})

onBeforeUnmount(() => {
  // 组件卸载前执行的逻辑
})

onUnmounted(() => {
  // 组件卸载后执行的逻辑
})

onErrorCaptured((err, instance, info) => {
  // 捕获来自后代组件的错误
  console.error('组件错误:', err, info)
  return false // 阻止错误继续向上传播
})
</script>

<style lang="less" scoped>
.login-container {
  // 登录页面容器样式
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  
  .login-card {
    // 登录卡片样式
    width: 400px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 12px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
    
    .login-header {
      // 头部样式
      text-align: center;
      margin-bottom: 40px;
      
      .login-title {
        font-size: 28px;
        font-weight: 600;
        color: #333;
        margin-bottom: 8px;
      }
      
      .login-subtitle {
        font-size: 14px;
        color: #666;
      }
    }
    
    .login-form {
      // 表单样式
      .form-item {
        margin-bottom: 24px;
        
        .form-label {
          font-size: 14px;
          color: #333;
          margin-bottom: 8px;
          font-weight: 500;
        }
        
        .input-wrapper {
          width: 100%;
          
          :deep(.el-input) {
            .el-input__wrapper {
              border-radius: 8px;
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
              transition: all 0.3s ease;
              
              &:hover {
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
              }
              
              &.is-focus {
                box-shadow: 0 4px 12px rgba(103, 126, 234, 0.2);
              }
            }
          }
        }
        
        .button-wrapper {
          .login-button {
            width: 100%;
            height: 48px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            transition: all 0.3s ease;
            
            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 8px 20px rgba(103, 126, 234, 0.3);
            }
            
            &:active {
              transform: translateY(0);
            }
            
            &.is-loading {
              background: #999;
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-container {
    padding: 20px;
    
    .login-card {
      width: 100%;
      padding: 30px 20px;
    }
  }
}
</style>